package com.linkage.seapeak.activity.vote;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.Vote.EditVoteMemberGroupAdapter;
import com.linkage.jz.bankruptcy.utils.ScreenUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.activity.message.MultiSelectActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.net.VoteNetRequest;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.pojo.VoteGroup;
import com.linkage.seapeak.pojo.VoteUserListBean;
import com.linkage.seapeak.utils.ToastUtil;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 编辑选择表决成员 有分组
 * 返回值为 List<VoteGroup> 对应键名为 result
 */
public class EditVoteMemberGroupActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    private static final int REQUEST_CODE_MEMBER = 0xf1;
    private static final int REQUEST_CODE_MONEY = 0xf2;
    private String projectId;
    private String voteId;

    private AYSwipeRecyclerView mRecyclerView;
    private RelativeLayout emptyView;
    private View bottomLay;
    private EditVoteMemberGroupAdapter mDataAdapter;

    private int voteType;
    private int voteRule;

    private List<VoteGroup> mData;
    private List<Object> setData;

    private View addGroupView;
    private PopupWindow addNewGroupPop;

    private int mDataAddIndex = 0;
    private int moneyIndex = 0;

    private VoteGroup currentVoteGroup = null;

    int count = 0;
    int page = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_vote_voters_group, "表决人员");
        projectId = getIntent().getStringExtra("projectId");
        voteId = getIntent().getStringExtra("voteId");
        voteType = getIntent().getIntExtra("voteType", -1);
        voteRule = getIntent().getIntExtra("voteRule", -1);
        init();
        mRecyclerView.startLoadFirst();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MEMBER && resultCode == RESULT_OK && data != null) {
//            List<CrediterUser> userList = (List<CrediterUser>) data.getSerializableExtra("userList");
//            HashMap<String, String> parms = (HashMap<String, String>) data.getSerializableExtra("parms");
//            addVoteMember(parms, userList, mData.get(mDataAddIndex), data.getIntExtra("selectType", -1));
            loadFirst();
            notifyDataChanged();
        } else if (requestCode == REQUEST_CODE_MONEY && resultCode == RESULT_OK && data != null) {
            CrediterUser user = (CrediterUser) setData.get(moneyIndex);
            VoteGroup group = null;
            for (Object o : setData) {
                if (o instanceof VoteGroup) {
                    group = (VoteGroup) o;
                    break;
                }
            }
            if (group != null)
                turnMoney(user, data.getDoubleExtra("money", 0d), group.getId());
            else
                showToast("数据异常");
        }
    }

    public void init() {
        addGroupView = LayoutInflater.from(EditVoteMemberGroupActivity.this)
                .inflate(R.layout.pro_vote_add_group_dialog, null, false);
        mRecyclerView = findViewById(R.id.list);
        emptyView = findViewById(R.id.empty);
        bottomLay = findViewById(R.id.bottom_lay);

        mData = new ArrayList<>();
        setData = new ArrayList<>();
        mDataAdapter = new EditVoteMemberGroupAdapter(this, setData);
        mRecyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        mRecyclerView.setShowEmpty(false);
        mRecyclerView.setOnRefreshLoadLister(this);
        mRecyclerView.setAdapter(mDataAdapter);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddPop(null);
            }
        });

        mDataAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                VoteGroup item;
                Intent intent;
                switch (v.getId()) {
                    case R.id.load:
                        CrediterUser load = (CrediterUser) setData.get(position);
                        for (int i = position; i >= 0; i--) {
                            if (setData.get(i) instanceof VoteGroup) {
                                VoteGroup temp = ((VoteGroup) setData.get(i));
                                showProgress();
                                getEditVoteMember(temp, load);
                            }
                        }
                        break;
                    case R.id.item_group_root:
                        item = (VoteGroup) setData.get(position);
                        if (currentVoteGroup != null && item.getId().equals(currentVoteGroup.getId())) {
                            item.isExpand = !item.isExpand;
                            currentVoteGroup = null;
                            notifyDataChanged();
                        } else {
                            currentVoteGroup = item;
                            page = 1;
                            getEditVoteMember(currentVoteGroup);
                        }
                        break;
                    case R.id.item_add:
                        item = (VoteGroup) setData.get(position);
                        List<String> ids = new ArrayList<>();
                        if (item.getMembers() != null && item.getMembers().size() > 0) {
                            for (CrediterUser user : item.getMembers()) {
                                ids.add(user.getCreditorid());
                            }
                        }
                        mDataAddIndex = mData.indexOf(item);
                        intent = new Intent(EditVoteMemberGroupActivity.this, VoteMemberMultiSelectActivity.class);
                        intent.putExtra("projectId", projectId);
                        intent.putExtra("alreadySelectIds", (Serializable) ids);
                        intent.putExtra("voteGroup", (Serializable) item);
                        intent.putExtra("canSelectAlready", true);
                        intent.putExtra("voteId", voteId);
                        intent.putExtra("voteType", voteType);
                        intent.putExtra("grouped", "1");
                        startActivityForResult(intent, REQUEST_CODE_MEMBER);
                        break;
                    case R.id.btn_group_edit:
                        item = (VoteGroup) setData.get(position);
                        showAddPop(item);
                        break;
                    case R.id.btn_group_delete:
                        item = (VoteGroup) setData.get(position);
                        deleteVoteGroup(item);
                        break;
                    case R.id.voter_change:
                        moneyIndex = position;
                        intent = new Intent(EditVoteMemberGroupActivity.this, VoteTurnMoneyActivity.class);
                        intent.putExtra("money", ((CrediterUser) setData.get(moneyIndex)).getVoteMoney());
                        startActivityForResult(intent, REQUEST_CODE_MONEY);
                        break;
                    case R.id.btnDelete:
                        CrediterUser user = (CrediterUser) setData.get(position);
                        for (int i = position; i >= 0; i--) {
                            if (setData.get(i) instanceof VoteGroup) {
                                VoteGroup temp = ((VoteGroup) setData.get(i));
                                deleteUser(user, temp);
                            }
                        }
                        break;
                }
                notifyDataChanged();
            }
        });

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editComplete();
            }
        }, "完成", 0));
        findViewById(R.id.add_group).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddPop(null);
            }
        });
        findViewById(R.id.create_ids).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                VoteNetRequest.getMeetingNumber(getUserToken(), voteId, projectId, voteRule + "", new ResultCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        hideProgress();
                        showToast("生成成功", ToastUtil.TOAST_TYPE.SUCCESS);
                        getEditGroupList(null);
                    }

                    @Override
                    public void onFailed(String msg) {
                        showToast(msg);
                        hideProgress();
                    }
                });
            }
        });
    }

    /**
     * 重新计算，刷新
     */
    public void notifyDataChanged() {
        setData.clear();
        count = 0;
        if (mData != null && mData.size() > 0) {
            for (VoteGroup group : mData) {
                setData.add(group);
                if (currentVoteGroup != null) {
                    if (group.getId().equals(currentVoteGroup.getId()))
                        group.isExpand = true;
                    else
                        group.isExpand = false;
                }
                List<CrediterUser> members = group.getMembers();
                if (members != null && members.size() > 0 && group.isExpand) {
                    for (CrediterUser user : members)
                        setData.add(user);
                }
                if(group.getTotalNum() != 0) {
                    count = group.getTotalNum();
                }
//                try {
//                    count = group.getTotalCount();
//                }catch (Exception ex)
//                {
//                    ex.printStackTrace();
//                }
            }
        }
//        if()
        setTitle(count == 0 ? "表决人员" : "表决人员(" + count + ")");
        mRecyclerView.onFinishRequest(false, false);
        emptyView.setVisibility(mData.size() == 0 ? View.VISIBLE : View.GONE);
        bottomLay.setVisibility(mData.size() != 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 展示弹窗
     *
     * @param voteGroup
     */
    private void showAddPop(final VoteGroup voteGroup) {
        Button cancelButton = addGroupView.findViewById(R.id.btn_chancel_u);
        Button okButton = addGroupView.findViewById(R.id.btn_save_u);
        TextView title = addGroupView.findViewById(R.id.notice_title);
        final EditText nameEdit = addGroupView.findViewById(R.id.group_name_edit);
        final CheckBox checkCommon = (CheckBox) addGroupView.findViewById(R.id.check_common);
        final CheckBox checkDanbao = (CheckBox) addGroupView.findViewById(R.id.check_danbao);
        final CheckBox checkOther = (CheckBox) addGroupView.findViewById(R.id.check_other);
        final TextView tip = (TextView) addGroupView.findViewById(R.id.tip_tv);
        nameEdit.setText(voteGroup == null ? "" : voteGroup.getName());
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addNewGroupPop != null && addNewGroupPop.isShowing()) {
                    addNewGroupPop.dismiss();
                }
            }
        });
        title.setText(voteGroup == null ? "新建表决组" : "编辑表决组");

//        if(voteGroup == null)
//        {
//            okButton.setText("通知");
//        }else{
            okButton.setText("确定");
//        }

        checkCommon.setVisibility(voteGroup != null ? View.GONE : View.VISIBLE);
        checkDanbao.setVisibility(voteGroup != null ? View.GONE : View.VISIBLE);
        checkOther.setVisibility(voteGroup != null ? View.GONE : View.VISIBLE);
        tip.setVisibility(voteGroup != null ? View.GONE : View.VISIBLE);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nameEdit.getText().length() == 0) {
                    showToast("名称不可以为空");
                    return;
                }

                if (voteGroup == null) {
                    if (!checkCommon.isChecked() && !checkDanbao.isChecked()
                            && !checkOther.isChecked()) {
                        showToast("必须选择一个类型！");
                        return;
                    }

                    VoteGroup item = new VoteGroup();
                    item.setName(nameEdit.getText().toString());
                    item.setOrdinary(checkCommon.isChecked());
                    item.setGuarantee(checkDanbao.isChecked());
                    item.setOther(checkOther.isChecked());
                    addVoteGroup(item);
                } else {
                    editVoteGroup(voteGroup, nameEdit.getText().toString());
                }

                notifyDataChanged();
                if (addNewGroupPop != null && addNewGroupPop.isShowing()) {
                    addNewGroupPop.dismiss();
                }
            }
        });
        if (addNewGroupPop == null || !addNewGroupPop.isShowing()) {
            addNewGroupPop = new PopupWindow(addGroupView,
                    ScreenUtils.getScreenWidth(EditVoteMemberGroupActivity.this) - 200,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
            //产生背景变暗效果
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.4f;
            getWindow().setAttributes(lp);
            //点击外面popupWindow消失
            addNewGroupPop.setOutsideTouchable(true);
            //popupWindow获取焦点
            addNewGroupPop.setFocusable(true);
            //popupWindow设置背景图
            addNewGroupPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.pro_vote_gray_light)));
            //popupWindow设置开场动画风格
            //popupWindow.setAnimationStyle(R.style.popupWindow_anim);
            //刷新popupWindow
            //popupWindow.update();

            //设置popupWindow消失时的监听
            addNewGroupPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                //在dismiss中恢复透明度
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
                    lp.alpha = 1f;
                    getWindow().setAttributes(lp);
                }
            });
            addNewGroupPop.showAtLocation(emptyView.getRootView(), Gravity.CENTER, 0, 0);
        } else {
            //如果popupWindow正在显示，接下来隐藏
            if (addNewGroupPop.isShowing()) {
                addNewGroupPop.dismiss();
            } else {
                //产生背景变暗效果
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.4f;
                getWindow().setAttributes(lp);
                addNewGroupPop.showAtLocation(emptyView.getRootView(), Gravity.CENTER, 0, 0);
            }
        }
    }

    /**
     * 设置金额
     *
     * @param user
     * @param money
     */
    private void turnMoney(final CrediterUser user, final double money, String groupId) {
        showProgress();
        VoteNetRequest.turnVoteMoney(getUserToken(), user.getId(), money, voteId, groupId, new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                user.setVoteMoney(money);
                user.setDeclareAsVote(false);
                notifyDataChanged();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 添加表决分组
     *
     * @param group
     */
    private void addVoteGroup(final VoteGroup group) {
        showProgress();
        VoteNetRequest.addVoteGroup(getUserToken(), voteId, group.getName(), group.isOrdinary(),
                group.isGuarantee(), group.isOther(), new ResultCallBack<VoteGroup>() {
                    @Override
                    public void onSuccess(VoteGroup result) {
                        hideProgress();
                        mData.add(result);
                        notifyDataChanged();
                    }

                    @Override
                    public void onFailed(String msg) {
                        hideProgress();
                        showToast(msg);
                    }
                });
    }

    /**
     * 修改表决分组
     *
     * @param group
     */
    private void editVoteGroup(final VoteGroup group, final String groupName) {
        showProgress();
        VoteNetRequest.editVoteGroup(getUserToken(), voteId, group.getName(), group.getId(),
                new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                group.setName(groupName);
                notifyDataChanged();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }


    /**
     * 删除表决分组
     *
     * @param group
     */
    private void deleteVoteGroup(final VoteGroup group) {
        showProgress();
        VoteNetRequest.deleteVoteGroup(getUserToken(), group.getId(), voteId, new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                showToast("删除分组成功", ToastUtil.TOAST_TYPE.SUCCESS);
                mData.remove(group);
                notifyDataChanged();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 完成修改
     */
    private void editComplete() {

        if(count == 0)
        {
            noticeDialog = new PublicNoticeDialog(EditVoteMemberGroupActivity.this, new View.OnClickListener(){

                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.ll_close:
                            noticeDialog.dismiss();
                            break;
                        case R.id.btn_chancel_notice:
                            noticeDialog.dismiss();
                            if (count != 0)
                                clearVoteMember();
                            else
                                finish();
                            break;
                        case R.id.btn_save_notice:
                            noticeDialog.dismiss();
                            if (count != 0)
                                editComplete();
                            break;
                    }
                }
            }, 1,"提示",count != 0 ? "是否保存选择的表决成员？" : "还没有添加任何成员哦~",
                    count != 0 ?  "不保存" : "暂不添加",count != 0 ? "保存" : "去添加");
            noticeDialog.show();
            return;
        }

        showProgress();
        VoteNetRequest.editComplete(getUserToken(), voteId, projectId, voteRule + "", new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                Intent intent = new Intent();
//                intent.putExtra("result", (Serializable) mData);
                intent.putExtra("count", count);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 添加人员
     *
     * @param userList
     */
    private void addVoteMember(HashMap<String, String> parms, final List<CrediterUser> userList, final VoteGroup temp, int type) {
//        showProgress();
        loadFirst();
//        VoteNetRequest.addGroupVoteMember(getUserToken(), parms, type, voteId, projectId, temp.getId(), userList,
//                temp.isOrdinary(), temp.isGuarantee(), temp.isOther(), new ResultCallBack<String>() {
//                    @Override
//                    public void onSuccess(String result) {
//                        hideProgress();
////                        if (temp.getMembers() == null)
////                            temp.setMembers(userList);
////                        else
////                            temp.getMembers().addAll(userList);
////                        temp.setMemberCount(temp.getMemberCount() + userList.size());
//                        getEditGroupList(temp);
//                        notifyDataChanged();
//                    }
//
//                    @Override
//                    public void onFailed(String msg) {
//                        hideProgress();
//                        showToast(msg);
//                    }
//                });
    }

    /**
     * 删除人员
     *
     * @param user
     */
    private void deleteUser(final CrediterUser user, final VoteGroup temp) {
        showProgress();
        VoteNetRequest.deleteVoteMember(getUserToken(), voteId, user.getId(), new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
//                temp.setMemberCount(temp.getMemberCount() - 1);
//                temp.getMembers().remove(user);
                showToast("删除成员成功", ToastUtil.TOAST_TYPE.SUCCESS);
//                notifyDataChanged();
                loadFirst();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
                showToast(msg);
            }
        });
    }

    /**
     * 获取列表
     */
    private void getEditVoteMember(final VoteGroup group) {
        getEditVoteMember(group, null);
    }
    private void getEditVoteMember(final VoteGroup group, CrediterUser user) {
        VoteNetRequest.getOrAddVoteMemberTable(getUserToken(), voteId, group.getId(), page + "",
                projectId, "", new ResultCallBack<VoteUserListBean>() {
                    @Override
                    public void onSuccess(VoteUserListBean result) {
                        hideProgress();
                        if (page == 1 && group.getMembers() != null)
                            group.getMembers().clear();
                        else if (group.getMembers() != null) {
                            if (user != null)
                                group.getMembers().remove(user);
                        }
                        page++;

                        if (group.getMembers() != null) {
                            group.getMembers().addAll(result.getList());
                        } else
                            group.setMembers(result.getList());
                        if (result.getCount() > group.getMembers().size())
                            group.getMembers().add(new CrediterUser("loadMore"));
                        group.setMemberCount(result.getCount());
                        group.setTotalCount(result.totalCount);
//                如果全部获取成功了就刷新列表页面
                        notifyDataChanged();
                    }

                    @Override
                    public void onFailed(String msg) {
                        notifyDataChanged();
                    }
                });
    }

    /**
     * 获取群组列表
     */
    private void getEditGroupList(VoteGroup group) {
        VoteNetRequest.getOrAddVoteGroupMemberTable(getUserToken(), voteId,
                projectId, voteRule == -1 ? "" : voteRule + "", new ResultCallBack<List<VoteGroup>>() {
                    @Override
                    public void onSuccess(List<VoteGroup> result) {
                        mData.clear();
                        mData.addAll(result);
                        for (int i = 0; i < mData.size(); i++) {
                            if (group != null) {
                                if (group.getId().equals(mData.get(i).getId())) {
                                    currentVoteGroup = mData.get(i);
//                                    mData.get(i).isExpand = true;
                                    page = 1;
                                    getEditVoteMember(mData.get(i));
                                }
                            } else {
                                if (i == 0) {
                                    currentVoteGroup = mData.get(i);
//                                    mData.get(i).isExpand = true;
                                    page = 1;
                                    getEditVoteMember(mData.get(i));
                                }
                            }

                        }
                        notifyDataChanged();
                    }

                    @Override
                    public void onFailed(String msg) {
                        notifyDataChanged();
                    }
                });
    }

    @Override
    public void loadFirst() {
        if (currentVoteGroup != null)
            getEditGroupList(currentVoteGroup);
        else
            getEditGroupList(null);
    }

    @Override
    public void loadNext() {

    }

    /**
     * 清空人员
     */
    private void clearVoteMember() {
        showProgress();
        VoteNetRequest.clearVoteMember(getUserToken(), voteId, new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgress();
                count = 0;
                finish();
            }

            @Override
            public void onFailed(String msg) {
                hideProgress();
//                finish();
                showToast(msg);
            }
        });
    }

    private PublicNoticeDialog noticeDialog;

    @Override
    public void backEvent() {
        noticeDialog = new PublicNoticeDialog(EditVoteMemberGroupActivity.this, new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_close:
                        noticeDialog.dismiss();
                        break;
                    case R.id.btn_chancel_notice:
                        noticeDialog.dismiss();
                        if (count != 0)
                            clearVoteMember();
                        else
                            finish();
                        break;
                    case R.id.btn_save_notice:
                        noticeDialog.dismiss();
                        if (count != 0)
                            editComplete();
                        break;
                }
            }
        }, 1,"提示",count != 0 ? "是否保存选择的表决成员？" : "还没有添加任何成员哦~",
                count != 0 ?  "不保存" : "暂不添加",count != 0 ? "保存" : "去添加");
        noticeDialog.show();
    }
}
